package com.lp.controller;

import com.lp.po.User;
import com.lp.service.UserService;
import com.lp.utils.Depository;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 包含Web端以及微信小程序端登录
 */
@Controller
public class LoginController {

    @Resource
    private UserService userService;
    UsernamePasswordToken token;
    Subject subject;
    //登录跳转
    @RequestMapping(value = "/login", method = {RequestMethod.GET})
    public String loginUI() throws Exception {
        return "login";
    }

    @RequestMapping(value="/logout",method = {RequestMethod.GET})
    public String logout() throws Exception{
        return "login";
    }

    @RequestMapping(value = "/wxlogin", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Map<String,String>  wxlogin(User user, Model model) throws Exception{

        Map<String,String> map = new HashMap<String, String>();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        if (subject.hasRole("admin")) {
            map.put("role","admin");
            map.put("username",user.getUsername());
        } else if (subject.hasRole("student")) {
            map.put("role","student");
            map.put("username",user.getUsername());
        }
        return map;

    }

    //登录表单处理
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public String login(User user,Model model) throws Exception {
        //保存用户名
        Depository depository=new Depository();
        String username=user.getUsername();
        depository.setUSERNAME(username);
        //获取当前登陆用户
        subject = SecurityUtils.getSubject();
        //封装表单中提交的用户名和密码
        token= new UsernamePasswordToken(user.getUsername(), user.getPassword());
        //调用login方法，传入封装好的token
        subject.login(token);
        //Shiro实现登录
        if (subject.hasRole("admin")) {
            model.addAttribute("username",username);
            return "admin/loginsuccess";
        } else if (subject.hasRole("student")) {
            model.addAttribute("username",username);
            return "student/loginsuccess";
        }else {
            return "login";
        }
    }

}
